from django.db import models
from django.urls import reverse
import uuid
from django.contrib.auth.models import User
from datetime import date
from django.core.validators import MinValueValidator, MaxValueValidator
from django.db.models import Avg

class Author(models.Model):
    """作者模型"""
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=100)
    date_of_birth = models.DateField(null=True, blank=True)
    date_of_death = models.DateField('Died', null=True, blank=True)
    bio = models.TextField(max_length=2000, help_text='作者简介', null=True, blank=True)
    photo = models.ImageField(upload_to='authors/', null=True, blank=True)

    class Meta:
        ordering = ['last_name', 'first_name']

    def get_absolute_url(self):
        return reverse('author-detail', args=[str(self.id)])

    def __str__(self):
        return f'{self.last_name}, {self.first_name}'

class Genre(models.Model):
    """图书类型模型"""
    name = models.CharField(max_length=200, help_text='输入图书类型（如科幻、诗歌等）')

    def __str__(self):
        return self.name

class Book(models.Model):
    """图书模型"""
    title = models.CharField(max_length=200)
    author = models.ForeignKey(Author, on_delete=models.SET_NULL, null=True)
    summary = models.TextField(max_length=1000, help_text='简单描述一下这本书')
    isbn = models.CharField('ISBN', max_length=13, unique=True, 
                            help_text='13位<a href="https://www.isbn-international.org/content/what-isbn">ISBN号码</a>')
    genre = models.ManyToManyField(Genre, help_text='选择这本书的类型')
    cover = models.ImageField(upload_to='covers/', null=True, blank=True, help_text='上传书籍封面')
    price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, help_text='书籍价格')
    publication_date = models.DateField(null=True, blank=True, help_text='出版日期')
    likes = models.ManyToManyField(User, related_name='book_likes', blank=True)
    favorites = models.ManyToManyField(User, related_name='book_favorites', blank=True)
    
    def __str__(self):
        return self.title

    def get_absolute_url(self):
        return reverse('book-detail', args=[str(self.id)])
    
    def get_average_rating(self):
        return self.review_set.aggregate(Avg('rating'))['rating__avg'] or 0
    
    def total_likes(self):
        return self.likes.count()
    
    def total_favorites(self):
        return self.favorites.count()

class BookInstance(models.Model):
    """图书实例模型，代表图书的特定副本（可借阅）"""
    id = models.UUIDField(primary_key=True, default=uuid.uuid4, 
                          help_text='图书馆中每本书的唯一编号')
    book = models.ForeignKey(Book, on_delete=models.RESTRICT, null=True)
    imprint = models.CharField(max_length=200)
    due_back = models.DateField(null=True, blank=True)
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True, blank=True)
    borrow_date = models.DateField(null=True, blank=True)

    LOAN_STATUS = (
        ('m', '维护中'),
        ('o', '已借出'),
        ('a', '可借阅'),
        ('r', '已预约'),
    )

    status = models.CharField(
        max_length=1,
        choices=LOAN_STATUS,
        blank=True,
        default='m',
        help_text='图书可用性',
    )

    class Meta:
        ordering = ['due_back']
        permissions = (("can_mark_returned", "设置图书为已归还"),
                       ("can_view_all_borrowed", "查看所有借出的图书"),)

    @property
    def is_overdue(self):
        return bool(self.due_back and date.today() > self.due_back)

    def __str__(self):
        return f'{self.id} ({self.book.title})'

class Review(models.Model):
    """书评模型"""
    book = models.ForeignKey(Book, on_delete=models.CASCADE)
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    rating = models.IntegerField(validators=[MinValueValidator(1), MaxValueValidator(5)])
    comment = models.TextField(max_length=1000)
    created_date = models.DateTimeField(auto_now_add=True)
    
    class Meta:
        ordering = ['-created_date']
        unique_together = ('book', 'user')  # 每个用户对每本书只能有一条评论
    
    def __str__(self):
        return f'{self.user.username}对{self.book.title}的评论'

class UserProfile(models.Model):
    """用户配置文件"""
    user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile')
    bio = models.TextField(max_length=500, blank=True)
    avatar = models.ImageField(upload_to='avatars/', null=True, blank=True)
    reading_preferences = models.ManyToManyField(Genre, blank=True, related_name='user_preferences')
    
    def __str__(self):
        return f'{self.user.username}的配置文件'

class BorrowHistory(models.Model):
    """借阅历史记录"""
    book_instance = models.ForeignKey(BookInstance, on_delete=models.SET_NULL, null=True)
    borrower = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
    borrow_date = models.DateField()
    return_date = models.DateField(null=True, blank=True)
    
    class Meta:
        ordering = ['-borrow_date']
        verbose_name_plural = "Borrowing histories"
    
    def __str__(self):
        return f'{self.borrower.username}借阅了{self.book_instance.book.title}'
